package com.tool.genxml.entity;

import cn.hutool.core.bean.BeanUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: zhoubin
 * @date: 2024/3/26
 */
public class XSheet {

    /**
     * sheet页名
     */
    private String name;

    /**
     * 每列中的数据
     */
    private List<XRow> rows;

    public XSheet(String name) {
        this.name = name;
        this.rows = new ArrayList<>();
    }

    /**
     * 添加数据
     * @param row
     */
    public void addRow(XRow row) {
        rows.add(row);

        // 当有属性时多建一条属性的配置数据
        if (!row.isCyclic() && row.isHasAttr()) {
            XRow attrRow = BeanUtil.toBean(row, XRow.class);
            attrRow.setXPath(row.getXPath() + "/@" + row.getAttrName());
            attrRow.setAttr(true);
            rows.add(attrRow);
        }
    }

    public void createSheet(XSSFWorkbook workbook) {
        XSSFSheet sheet = workbook.createSheet(name);

        XSSFRow title = sheet.createRow(0);
        title.createCell(0).setCellValue("node_path");
        title.createCell(1).setCellValue("father_path");
        title.createCell(2).setCellValue("node_notes");
        title.createCell(3).setCellValue("node_order");
        title.createCell(4).setCellValue("cyclic_field_flag");
        title.createCell(5).setCellValue("sign_flag");
        title.createCell(6).setCellValue("attribute_flag");

        for (int i = 0; i < rows.size(); i++) {
            XRow xRow = rows.get(i);
            XSSFRow row = sheet.createRow(i + 1);
            row.createCell(0).setCellValue(xRow.getXPath());
            row.createCell(1).setCellValue(xRow.getParentPath());
            row.createCell(2).setCellValue(xRow.getNotes());
            row.createCell(3).setCellValue((i + 1) * 10);
            row.createCell(4).setCellValue(xRow.isCyclic() ? 1 : 0);
            row.createCell(5).setCellValue(xRow.isSign() ? 1 : 0);
            row.createCell(6).setCellValue(xRow.isAttr() ? 1 : 0);
        }
    }
}
